// 导入基础数据
// 是否自动初始化
var autoPlay = false;
// SKU过滤规则
var skuFilter = ["尺寸", "尺码", "大小"];
var skuKindNum = 0;
// 库存
var stock = "1000";
// 商品重量
var spzl = 0.01;
// 商品尺寸
var spcc = [1, 1, 1];
// 物流方式
var wlfs = [
  "蝦皮海外 - 宅配 (max 20kg)",
  // "蝦皮海外 - 7-11 (max 10kg)",
  // "蝦皮海外 - 全家 (max 10kg)",
  // "蝦皮海外 - 萊爾富（空運） (max 10kg)",
];
var timestamp = new Date().getTime();
var $$;

// 通用SKU
var generalSku = "🌈其他尺寸請看描述價格下單唷";

// 是否在运行中
var isRunning = false;

let kyy = {
  tbRate: 3.5,
  dateStr: "20000101",
};
// 次要SUK index  有通用SKU种类
var subSkuIndex;

var pddData = {
  goods: [],
  // 价格类型 1 运费公式 2 价格*5
  priceType: "1",
  // 第一个SKU
  firstSku: "30*40",
  // 初始价
  originalPrice: "1872",
  // 商品标题
  goodsTitle: "~~~~",
  // 商品描述
  goodsDesc: "~~~~",
  // 第一个分类描述
  firstClassify: "",
  // 初始化的分类描述 根据是否为空可判断是否只有一个SKU
  filterSkuKind: "",
  pddKeyWordDes: "",
  goodsDetails: [],
};

function selectTW(timeout = 2000) {
  // 台湾站点按钮
  return new Promise((resolve, reject) => {
    var twBtn = document.querySelectorAll(
      "#main .v-content__wrap .v-tabs__item"
    )[1];
    twBtn.click();
    setTimeout(async () => {
      // 选择店铺
      await selectItem("Lily-house 🎀北歐家居館");

      resolve();
    }, timeout);
  });
}

// 下拉框选择按钮
function selectItem(itemName, timeout = 500) {
  return new Promise((resolve, reject) => {
    //如果选项有重复项需小心~~~~~！！！！
    Array.from($("#appRoot  .v-select-list .v-list__tile__title")).forEach(
      (item) => {
        if (item.textContent == itemName) {
          item.click();
        }
      }
    );

    Array.from($("#appRoot .v-cascader-list .v-list__tile__title")).forEach(
      (item) => {
        if (item.textContent.includes(itemName)) {
          item.click();
        }
      }
    );

    setTimeout(() => {
      resolve();
    }, timeout);
  });
}

// 修改input标签
function updateInput(handle, val) {
  return new Promise((resolve, reject) => {
    // 找到句柄
    handle = handle.next();

    handle.find(".v-input__control").click(async (e) => {
      await wait(500);

      // 点击后出来input才能执行，需要放在timeout中
      var inputHandle =
        handle.find("textarea").length > 0
          ? handle.find("textarea")[0]
          : handle.find("input")[0];
      await inputValue(inputHandle, val);
      // 清除事件
      handle.find(".v-input__control").unbind(e);
      resolve();
    });

    // 手动触发
    handle.find(".v-input__control")[0].click();
  });
}

// 设置通用价格
async function initGeneralPrice() {
  let temps = getHandleBySelectorAndText($(".v-table td"), generalSku, true);
  // 判断价格模板类型
  switch (pddData.priceType) {
    // 价格类型为运费模板
    case "1": {
      break;
    }
    // 价格5倍
    case "2": {
      // 遍历出最高价
      let trList = $('div[title="商品规格列表"]').next().find("tbody tr");
      let maximalPrice = 0;
      let trPrice = 0;
      let temp = "";

      for (var j = 0; j < trList.length; j++) {
        // 获取每一列第一个input的值，就是价格
        trPrice = trList
          .eq(j)
          .find(".k-text-field-content-value__text")
          .eq(0)
          .text();
        trPrice = trPrice == "" ? 0 : parseFloat(trPrice);
        // 获取最大值
        maximalPrice = maximalPrice > trPrice ? maximalPrice : trPrice;
      }

      for (var i = 0; i < temps.length; i++) {
        temp =
          temps[i].next().find(".k-text-field__input").length > 0
            ? temps[i].next().find(".k-text-field__input")[0]
            : temps[i].next().next().find(".k-text-field__input")[0];
        await inputValue(temp, (parseFloat(maximalPrice) / 4.5).toFixed(2));
      }
      break;
    }
    default: {
      break;
    }
  }
}

// 设置input值
function inputValue(el, val) {
  return new Promise((resolve, reject) => {
    setTimeout(() => {
      let evt = document.createEvent("HTMLEvents");
      evt.initEvent("input", true, true);
      el.value = val;
      el.dispatchEvent(evt);
      resolve();
    }, 300);
  });
}

// 通用价格设置价格
async function setOriginPrice() {
  let temp = getHandleBySelectorAndText($(".v-table td"), generalSku);
  temp =
    $(temp).next().find(".k-text-field__input").length > 0
      ? $(temp).next().find(".k-text-field__input")
      : $(temp).next().next().find(".k-text-field__input");
  await inputValue(temp[0], Math.ceil(temp.eq(0).val() / 4));
}

// 设置价格
async function setTargetPrice() {
  let temp = parseInt(
    $("#variationTableRow1 .k-text-field-content-value__text").text()
  );
  let value = Math.ceil(temp / 5 / 100) > 10 ? Math.ceil(temp / 5 / 100) : 10;
  let node = $('div[title="商品规格列表"]').next().find(".k-text-field__input");
  await inputValue(node[5], value);
}

// 设置checkBox
function checkBox(el, attr, val) {
  return new Promise((resolve, reject) => {
    setTimeout(() => {
      if (attr == val + "") {
        el.click();
      }
      resolve();
    }, 50);
  });
}

function getTbRate() {
  return $("#tbRate").val();
}

function getHandleBySelectorAndText(selector, text, isArray = false) {
  let handle = typeof selector == "String" ? $(selector) : selector;
  let len = handle.length;
  let temp;
  let arr = [];

  if (isArray) {
    for (var i = 0; i < len; i++) {
      temp = handle.eq(i).text();
      if (temp.includes(text)) {
        arr.push(handle.eq(i));
      }
    }
    return arr;
  } else
    for (var i = 0; i < len; i++) {
      temp = handle.eq(i).text();
      if (temp.includes(text)) {
        return handle.eq(i);
      }
    }
}


async function test() {
  // await selectItem(" Home & Living (家居和生活) ", 500);
  // await selectItem(" Decoration (装修) ", 500);
  // await selectItem(" Furniture & Appliance Covers (家具和家电覆盖) ", 2000);
  // await selectItem("NoBrand(NoBrand)");
  // await selectItem("其他(其他)");
  // await selectItem("否(否)");


  let allCheck = $('div[title="商品规格列表"]').next().find("th").eq(0).find("input");
  allCheck[0].setAttribute("id", "allCheck");

  console.log("hello~!");
}

async function initRate() {
  console.log("initRateBtn");

  var firstBtn = $('#main .v-tabs__item:contains("源数据")')[0];
  console.log(firstBtn);
  firstBtn.click();

  await wait(2000);

  anchors("物流信息");
  await wait(1000);
  anchors("价格库存");
  await wait(2000);
  anchors("物流信息");
  await wait(2000);
  // 表头
  var ths = Array.from($("#variation-table thead th"));
  // 价格索引
  var idx = -1;
  console.log(ths);
  ths.forEach((e, index) => {
    if (e.textContent.includes("价格")) {
      idx = index;
    }
  });
  console.log("idx:", idx);
  console.log($("#variation-table tbody td").eq(idx).find("span"));
  console.log(
    $("#variation-table tbody td")
      .eq(idx)
      .find(".k-text-field-content-value__text")
  );
  console.log(idx);
  // 获取表身第一个价格
  var price1 =
    $("#variation-table tbody td")
      .eq(idx)
      .find(".k-text-field-content-value__text").length == 0
      ? $("#variation-table tbody td").eq(idx).find("span")[0].textContent
      : $("#variation-table tbody td")
        .eq(idx)
        .find(".k-text-field-content-value__text")[0].textContent;
  console.log(price1);

  // ------------------------------- //
  var secondBtn = $('#main .v-tabs__item:contains("台湾站")')[0];
  secondBtn.click();

  await wait(2000);

  anchors("价格库存");
  await wait(2000);
  anchors("物流信息");
  await wait(2000);

  var price2 =
    $("#variation-table tbody td")
      .eq(idx)
      .find(".k-text-field-content-value__text").length == 0
      ? $("#variation-table tbody td").eq(idx).find("span")[0].textContent
      : $("#variation-table tbody td")
        .eq(idx)
        .find(".k-text-field-content-value__text")[0].textContent;

  let twRate = price2 / price1;

  $("#tbRate").val(twRate);
  $("#tbRate").trigger("change");
}


// 客优云弄个固定窗口存放按钮
async function initBox() {
  var kyyBox = document.createElement("div");
  kyyBox.setAttribute("class", "kyyBox");
  document.body.appendChild(kyyBox);

  $(".kyyBox").append(
    '<div class="kkyContent">' +
    '台币汇率：<input id="tbRate" class="tbRate">' +
    '<button class="initRateBtn pddBtn">初始化汇率</button>' +
    "<br>" +
    '<textarea rows="5" class="textarea">请替换拼多多一键打包的数据，采集页面才需要~~~</textarea>' +
    "<br>" +
    '<button class="collectBtn pddBtn">一键采集默认折扣</button>' +
    "<br>" +
    "------------辅助功能------------" +
    "<br>" +
    '<button class="initBtn pddBtn">一键初始化(基础数据)</button>' +
    "<br>" +
    '<button class="refreshBtn pddBtn">刷新库存</button>' +
    '<button class="clearBtn pddBtn">清空库存</button>' +
    "<br>" +
    '<button class="testBtn pddBtn">test</button>' +
    "<br>" +
    '打折数：<input id="discountInput" value="50" />' +
    '<button class="goodsBtn pddBtn">一键折扣</button>' +
    "<br>" +
    '物流天数：<input id="expressInput" value="5"></input>' +
    '<button class="expressBtn pddBtn">初始化物流</button>' +
    "</div>"
  );

  await wait(500);
  $(".textarea").bind("input propertychange", () => {
    let data = JSON.parse($(".textarea").eq(0).val());
    pddData.firstSku = data.firstSku;
    pddData.originalPrice = data.originalPrice;

    pddData.goodsTitle = data.goodsTitle;
    pddData.skuKindNum = data.skuKindNum;
    pddData.firstClassify = data.firstClassify;
    pddData.filterSkuKind = data.filterSkuKind;
    pddData.goods = data.goods;
    pddData.priceType = data.priceType;
    pddData.pddKeyWordDes = data.pddKeyWordDes;
    pddData.goodsDetails = data.goodsDetails;
    pddData.goodsDesc = data.goodsDesc;

    skuFilter.push(data.filterSkuKind);

    // 避免复制上上次的数据
    $copyText("请先拷贝拼多多一键打包数据，粘贴一次即可~~~");
  });

  // 一键采集按钮
  $(".collectBtn").click(async () => {

    if (!$("#tbRate").val()) {
      await initRate();
    }

    if (
      $(".textarea").eq(0).val() ==
      "请替换拼多多一键打包的数据，采集页面才需要~~~"
    ) {
      console.log("请先粘贴拼多多数据...");
      return;
    }

    if (isRunning) {
      console.log("isRunning...");
      return;
    }

    isRunning = true;

    await wait(1000);

    // 选择台湾站点
    await selectTW();

    // 遍历锚点，处理懒加载
    anchors();
    await wait(8000);

    // 获取台币汇率
    getTbRate();

    await initCollect();

    isRunning = false;
  });

  // 一键折扣
  $(".goodsBtn").click(async () => {
    if (isRunning) {
      console.log("isRunning...");
      return;
    }

    isRunning = true;

    await oneKeyDiscount($("#discountInput").val());

    // 自动更新
    getHandleBySelectorAndText($(".v-btn__content"), "更新").click();

    isRunning = false;
  });

  // 普通初始化
  $(".initBtn").click(async () => {
    if (isRunning) {
      console.log("isRunning...");
      return;
    }

    isRunning = true;

    await wait(1000);
    // 选择台湾站点
    await selectTW();

    initKyy();

    // 自动更新

    isRunning = false;
  });

  // 清空库存
  $(".clearBtn").click(async () => {
    if (isRunning) {
      console.log("isRunning...");
      return;
    }

    isRunning = true;

    anchors("定价工具");
    await wait(1000);

    // 库存
    var stockInput = $('div[title="批量编辑"]')
      .parent()
      .find('input[aria-label="库存"]')[0];
    await inputValue(stockInput, 0);

    // 批量编辑一键设置按钮
    var bulkBtn = getHandleBySelectorAndText(
      $(".v-btn__content"),
      "一键设置",
      true
    );
    bulkBtn[0].click();

    await wait(500);

    $(".anchors span").eq(5).trigger("click");
    await wait(200);

    // 点击折扣活动
    $('input[aria-label="折扣活动"]').click();
    await wait(500);

    // 点击确定按钮
    $("#inspire .v-btn__content")[3].click();
    await wait(1000);

    $("#priceAndStock div.v-chip__close").click();

    await wait(500);
    // 自动更新
    getHandleBySelectorAndText($(".v-btn__content"), "更新").click();

    isRunning = false;
  });

  // test
  $(".testBtn").click(async () => {
    if (isRunning) {
      console.log("isRunning...");
      return;
    }

    isRunning = true;

    await test();

    isRunning = false;
  });
  // 刷新库存
  $(".refreshBtn").click(async () => {
    if (isRunning) {
      console.log("isRunning...");
      return;
    }

    isRunning = true;

    // 时间间隔作为每日更新模板
    var s1 = "2021-05-27";
    s1 = new Date(s1.replace(/-/g, "/"));
    //当前日期
    s2 = new Date();
    var days = s2.getTime() - s1.getTime();
    var time = parseInt(days / (1000 * 60 * 60 * 24));

    anchors("定价工具");
    await wait(1000);

    // 库存
    var stockInput = $('div[title="批量编辑"]')
      .parent()
      .find('input[aria-label="库存"]')[0];
    await inputValue(stockInput, parseInt(stock) + time);

    // 批量编辑一键设置按钮
    var bulkBtn = getHandleBySelectorAndText(
      $(".v-btn__content"),
      "一键设置",
      true
    );
    bulkBtn[0].click();

    await wait(500);

    // 自动更新
    getHandleBySelectorAndText($(".v-btn__content"), "更新").click();
    isRunning = false;
  });

  // 初始化物流
  $(".expressBtn").click(async () => {
    if (isRunning) {
      console.log("isRunning...");
      return;
    }

    isRunning = true;

    anchors("物流信息");
    await wait(1000);

    let val = $("#expressInput").val();
    if (!val) {
      console.log("请先填写发货期限，默认3...");
      return;
    }

    // 物流信息
    await expressInfo();

    isRunning = false;
  });

  // 监听台湾倍率
  $("#tbRate").change(() => {
    kyy.tbRate = $("#tbRate").val();
    let date = new Date();
    kyy.dateStr = "";
    kyy.dateStr = "" + date.getFullYear();
    /**测试加上毫秒 */
    // kyy.dateStr += "" + date.getMilliseconds();
    kyy.dateStr += "" + (date.getMonth() + 1);
    kyy.dateStr += "" + date.getDate();
    localStorageSetItem("kyy", kyy);
  });

  // 监听运货期
  $("#expressInput").change((inputObj) => {
    let val = $("#expressInput").val();
    if (!/(^0$)|(^100$)|(^\d{1,2}$)/.test(val)) {
      val = parseInt(val);
      if (val > 30) {
        val = 30;
      }
      if (val < 3) {
        val = 3;
      }
    }
    val = parseInt(val);
    if (val > 30) {
      val = 30;
    }
    if (val < 3) {
      val = 3;
    }
    $("#expressInput").val(val);
  });

  // 初始化汇率
  $(".initRateBtn").click(initRate);
}

// 设置类目
async function initShopCategory() {
  switch (pddData.firstClassify) {
    case "Lily-家具贴纸": {
      // 也是家具覆盖
    }
    case "Lily-桌墊": {
      // 也是家具覆盖
    }
    case "Lily-椅套": {
      // 也是家具覆盖
    }
    case "Lily-沙發墊": {
      await selectItem(" Home & Living (家居和生活) ", 500);
      await selectItem(" Decoration (装修) ", 500);
      await selectItem(" Furniture & Appliance Covers (家具和家电覆盖) ", 2500);

      break;
    }
    case "Lily-窗簾": {
      await selectItem(" Home & Living (家居和生活) ", 500);
      await selectItem(" Decoration (装修) ", 500);
      await selectItem(" Curtains & Blinds (窗帘和百叶窗) ", 2500);

      break;
    }
    case "Lily-地墊": {
      await selectItem(" Home & Living (家居和生活) ", 500);
      await selectItem(" Decoration (装修) ", 500);
      await selectItem("Carpets & Rugs (地毯和地毯)", 2500);

      break;
    }
    case "Lily-床上用品": {
      await selectItem(" Home & Living (家居和生活) ", 500);
      await selectItem("Bedding (床上用品)", 500);
      await selectItem(
        "Bedsheets, Pillowcases & Bolster Cases (床单枕套和鞋垫案例)",
        2500
      );

      break;
    }
    case "Lily-壁紙": {
      await selectItem(" Home & Living (家居和生活) ", 500);
      await selectItem(" Decoration (装修) ", 500);
      await selectItem(" Wallpapers & Wall Stickers (壁纸和墙壁贴纸) ", 2500);

      break;
    }
    case "Lily-挂鈎": {
      await selectItem(" Home & Living (家居和生活) ", 500);
      await selectItem(" Home Organizers (家庭组织者) ", 500);
      await selectItem(" Hooks (挂钩) ", 2500);

      break;
    }
    case "Lily-浴簾": {
      await selectItem(" Home & Living (家居和生活) ", 500);
      await selectItem(" Bathrooms (浴室) ", 500);
      await selectItem(" Shower Curtains (淋浴窗帘) ", 2500);

      break;
    }
    case "Lily-收納盒": {
      await selectItem(" Home & Living (家居和生活) ", 500);
      await selectItem(" Home Organizers (家庭组织者) ", 500);
      await selectItem(
        " Storage Boxes, Bags & Baskets (储物箱包和篮子) ",
        2500
      );

      break;
    }
    case "Lily-門簾": {
      await selectItem(" Home & Living (家居和生活) ", 500);
      await selectItem(" Tools & Home Improvement (工具和家居装修) ", 500);
      await selectItem(" Doors & Windows (门窗) ", 2500);

      break;
    }
    case "Lily-墙壁装饰": {
      await selectItem(" Home & Living (家居和生活) ", 500);
      await selectItem(" Tools & Home Improvement (工具和家居装修) ", 500);
      await selectItem(" Photo Frames & Wall Decoration (光涂层和墙壁装饰) ", 2500);

      break;
    }
    case "Lily-其他": {
      await selectItem(" Home & Living (家居和生活) ", 500);
      await selectItem(" Others (其他) ", 2500);

      break;
    }
    // -----------------------------
    // case "Lily-掛畫": {
    //   await selectItem(" Home & Living (家居和生活) ", 500);
    //   await selectItem(" Bathrooms (浴室) ", 500);
    //   await selectItem(" Shower Curtains (淋浴窗帘) ", 2500);

    //   break;
    // }
    // case "Lily-相框": {
    //   await selectItem(" Home & Living (家居和生活) ", 500);
    //   await selectItem(" Decoration (装修) ", 500);
    //   await selectItem(" Floor Mats (地板垫) ", 2500);

    //   break;
    // }
    default: {
      await selectItem(" Home & Living (家居和生活) ", 500);
      await selectItem(" Others (其他) ", 500);

      break;
    }
  }

  await selectItem("NoBrand(NoBrand)");
  await selectItem("其他(其他)");
  await selectItem("否(否)");
  await selectItem("无保修(无保修)");
  await selectItem("中国大陆(中国大陆)");

  anchors("店铺类目");
}

// 编辑商品详情
function editGoodsDesc() {
  // // 设置商品描述前缀
  // let temp = dlData.prefix + "\n\n🔹🔹🔹🔹🔹🔹🔹🔹🔹🔹\n😀【商品详情】😀\n";

  // // 获取最长的SKU
  // let longestSkuLength = 0;
  // if (strlen(pddData.goods[pddData.goods.length - 1].sku) > longestSkuLength) {
  //   longestSkuLength = strlen(pddData.goods[pddData.goods.length - 1].sku);
  // }

  // // 添加商品详情属性
  // pddData.goodsDetails.forEach((e) => {
  //   temp += e + "\n";
  // });
  // temp += "🔹🔹🔹🔹🔹🔹🔹🔹🔹🔹";

  // 设置商品描述前缀
  let temp = dlData.prefix + "\n\n====================\n《【商品详情】》\n";

  // 获取最长的SKU
  let longestSkuLength = 0;
  if (strlen(pddData.goods[pddData.goods.length - 1].sku) > longestSkuLength) {
    longestSkuLength = strlen(pddData.goods[pddData.goods.length - 1].sku);
  }

  // 添加商品详情属性
  pddData.goodsDetails.forEach((e) => {
    temp += e + "\n";
  });
  temp += "====================";

  temp +=
    "\n\n【其他現貨尺寸下標指南】:如價格為290，下標先選擇對應花色，再選擇客製尺寸，數量欄輸入29即可！下单请备注尺寸\n\n【商品尺寸、价格】\n";

  // 添加SKU
  pddData.goods.forEach((element, index1) => {
    element.targetPrice = Math.floor(
      (element.originPrice * pddData.originalPrice * getTbRate()) / 2
    );

    let addSpaceNum = longestSkuLength - strlen(element.sku);
    let str = "";
    for (var i = 0; i < addSpaceNum; i++) {
      str = str + "\xa0";
    }
    temp += `${element.sku}\xa0\xa0\xa0\xa0${str}\xa0\xa0\xa0\xa0${element.targetPrice}元\n`;
  });

  // 添加后缀
  temp += dlData.suffix + "\n\n";

  // 添加关键词
  temp += pddData.pddKeyWordDes + "\n\n";

  return temp;
}

// 遍历锚点，处理懒加载
function anchors(target, timeout = 600) {
  if (target) {
    for (var i = 0; i < $(".anchors span").length; i++) {
      if ($(".anchors span").eq(i).text() == target) {
        $(".anchors span").eq(i).trigger("click");
        break;
      }
    }
    return;
  }
  for (var i = 0; i < $(".anchors span").length; i++) {
    !(function (i) {
      setTimeout(() => {
        $(".anchors span").eq(i).trigger("click");
      }, timeout * i);
    })(i);
  }
  setTimeout(() => {
    $(".anchors span").eq(0).trigger("click");
  }, timeout * $(".anchors span").length);
}

async function initCollect() {
  anchors("店铺类目");
  // 选择適用空間
  await selectItem("臥室(卧室)");

  // 选择風格
  await selectItem("歐式(欧式)");

  // 选择材质
  await selectItem("混紡(混纺)");

  // 选择品牌
  await selectItem("自有品牌(自有品牌)");
  anchors("商品信息");

  // 选择客优云分类
  await selectItem(pddData.firstClassify);

  // 修改商品title
  await addGoodsSuffix();
  // 添加商品编码
  await updateInput($('#appRoot  div[title="商品编码"]'), timestamp);
  // 添加商品描述
  await addGoodsDesc();

  anchors("价格库存");

  // 需要过滤才初始化SKU以及设置价格表
  // 初始化SKU
  await initSku();

  // 批量编辑
  await wait(500);
  await bulkEdit();


  await wait(500);
  await oneKeyDiscount();

  // 物流信息
  await wait(500);
  await expressInfo();

  // 初始化类目
  await wait(500);
  await initShopCategory();
}

// 修改商品title
function addGoodsSuffix() {
  return new Promise(async (resolve, reject) => {
    // 找到句柄
    let handle = $('#appRoot  div[title="商品名称"]').next();

    handle.find(".k-sensitive-words-input").click(async (e) => {
      await wait(500);

      // 清除事件
      // 点击后出来input才能执行，需要放在timeout中
      await inputValue(handle.find("input")[0], pddData.goodsTitle);
      handle.find(".k-sensitive-words-input").unbind(e);
      resolve();
    });

    // 手动触发
    handle.find(".k-sensitive-words-input__mask")[0].click();
  });
}


// 添加商品描述
function addGoodsDesc() {
  return new Promise(async (resolve, reject) => {
    // 找到句柄
    let handle = $('#appRoot  div[title="描述"]').next();

    handle.find(".k-sensitive-words-input").click(async (e) => {
      await wait(500);

      // 判断价格模板类型
      switch (pddData.priceType) {
        // 价格类型为运费模板
        case "1": {
          break;
        }
        // 价格5倍
        case "2": {
          pddData.goodsDesc = editGoodsDesc();
          break;
        }
        default: {
          console.log("设置折扣值:数据有问题~");
          break;
        }
      }

      // 点击后出来input才能执行，需要放在timeout中
      await inputValue(handle.find("textarea")[0], pddData.goodsDesc);
      // 清除事件
      handle.find(".k-sensitive-words-input").unbind(e);
      resolve();
    });

    // 手动触发
    handle.find(".k-sensitive-words-input__mask")[0].click();
  });
}


// 物流信息
async function expressInfo() {
  anchors("物流信息");
  // 商品重量
  var spzlInput = $("#logisticsInfo div[title=商品重量]")
    .next()
    .find("input")[0];
  inputValue(spzlInput, spzl);

  // 商品尺寸
  var spccInput = $("#logisticsInfo div[title=商品尺寸]").next().find("input");
  inputValue(spccInput[0], spcc[0]);
  inputValue(spccInput[1], spcc[1]);
  inputValue(spccInput[2], spcc[2]);

  for (let item of wlfs) {
    let handle = $(`#logisticsInfo input[aria-label="${item}"]`);
    if (handle.length > 0) {
      await checkBox(handle[0], handle[0].getAttribute("aria-checked"), false);
    }
  }

  // 发货期3天
  if (parseInt($("#expressInput").val()) == 3) {
    var deliveryDate = $('label[aria-hidden="true"]:contains("3天")');
    deliveryDate.click();
  } else {
    var deliveryDate = $('label[aria-hidden="true"]:contains("自定义")');
    deliveryDate.click();

    setTimeout(() => {
      // 发货期
      var input = $("input[suffix='DAYS']")[0];
      inputValue(input, $("#expressInput").val());
    }, 2000);
  }
}

async function initKyy() {
  anchors("店铺类目");
  // 选择適用空間
  await selectItem("臥室(卧室)");

  // 选择風格
  await selectItem("歐式(欧式)");

  // 选择材质
  await selectItem("混紡(混纺)");

  // 选择品牌
  await selectItem("自有品牌(自有品牌)");

  // 添加商品编码
  await updateInput($('#appRoot  div[title="商品编码"]'), timestamp);
  // 规格编码
  await inputValue($('input[aria-label="规格编码"]')[0], timestamp);

  anchors("物流信息");
  // 物流信息
  await expressInfo();
}


// 初始化SKU
async function initSku(timeout = 1000) {
  // 删除默认SKU
  async function deleteSku(deleteBtn, timeout = 100) {
    return new Promise(async (resolve, reject) => {
      await wait(timeout);
      deleteBtn.trigger("click");
      resolve();
    });
  }

  // 添加新的SKU
  function addSku(skuIndex, skuName) {
    return new Promise((resolve, reject) => {
      setTimeout(async () => {
        let skuHandle = $(".variation-option-creator:eq(" + skuIndex + ")")
          .find("input")
          .last()[0];
        await inputValue(skuHandle, skuName);
        resolve();
      }, 1000);
    });
  }

  return new Promise(async (resolve, reject) => {
    var handle = $(".variation-option-creator");
    let arr = Array.from(handle);
    /** 多余的价格相关SKU */
    let moreSkuSize = 0;
    switch (pddData.priceType) {
      case "1": {
        // 如果只有一个SKU
        if (pddData.filterSkuKind == "") {
          // 添加通用SKU
          $(".variation-option-creator:eq(0)").find("button").eq(0).click();
          await addSku(0, generalSku);
          resolve();
          return;
        }

        // 第一个SKU不能超过50个
        for (var ai = 0; ai < arr.length; ai++) {
          if (
            arr[ai].getElementsByTagName("input")[0].value !=
            pddData.filterSkuKind
          ) {
            let more =
              $(".variation-option-creator:eq(" + ai + ")").find(
                ".v-input__append-outer i"
              ).length - 25;
            for (var i = 0; i < more; i++) {
              await deleteSku(
                $(".variation-option-creator:eq(" + ai + ")")
                  .find(".v-input__append-outer i")
                  .last()
              );
            }
          }
        }
        for (var ai = 0; ai < arr.length; ai++) {
          if (
            arr[ai].getElementsByTagName("input")[0].value ==
            pddData.filterSkuKind
          ) {
            subSkuIndex = ai;
            while (
              $(".variation-option-creator:eq(" + ai + ")").find(
                ".v-input__append-outer i"
              )[0]
            ) {
              await deleteSku(
                $(".variation-option-creator:eq(" + ai + ")")
                  .find(".v-input__append-outer i")
                  .eq(0)
              );
            }

            // 添加第一个有用SKU
            $(".variation-option-creator:eq(" + ai + ")")
              .find("button")
              .eq(0)
              .click();
            await addSku(ai, pddData.firstSku);

            // 添加通用SKU
            $(".variation-option-creator:eq(" + ai + ")")
              .find("button")
              .eq(0)
              .click();
            await addSku(ai, generalSku);
          }
        }
        await wait(timeout);
        resolve();
        break;
      }
      case "2": {
        let minorSkuSize = 1;
        /** 1个SKU */
        if (pddData.filterSkuKind == "") {
          minorSkuSize = $(".variation-option-creator:eq(0)").find(
            ".v-input__append-outer i"
          ).length;
          let more1 = minorSkuSize - 49;

          // 价格5倍内
          // 获取最低价
          let miniPrice = pddData.goods[0].targetPrice;
          let maxPriceIndex = 0;
          // 遍历第几个后是5倍内，并获取其索引
          for (var gi = 0; gi < pddData.goods.length; gi++) {
            maxPriceIndex =
              pddData.goods[gi].targetPrice < 5 * miniPrice
                ? gi
                : maxPriceIndex;
          }

          // 重新拆分goods
          pddData.goods = pddData.goods.slice(0, maxPriceIndex + 1);

          let goodsLength = pddData.goods.length;
          let kyyGoods = $(".variation-option-creator:eq(0)").find(
            '.v-text-field__slot input[aria-label="选项"]'
          );
          let kyySkuLength = kyyGoods.length;
          let isExist = false;
          let delArr = [];

          // 排除无效的SKU
          for (var k = 0; k < kyySkuLength; k++) {
            isExist = false;
            for (var j = 0; j < goodsLength; j++) {
              if (kyyGoods.eq(k).val() == pddData.goods[j].sku) {
                isExist = true;
                break;
              }
            }
            if (!isExist) {
              delArr.unshift(k);
            }
          }

          // 删除掉无效的sku，从后往前删
          for (var di = 0; di < delArr.length; di++) {
            await deleteSku(
              $(".variation-option-creator:eq(0)")
                .find(".v-input__append-outer i")
                .eq(delArr[di])
            );
          }

          // 删除多余的SKU，只留下49个
          for (var i = 0; i < more1; i++) {
            await deleteSku(
              $(".variation-option-creator:eq(0)")
                .find(".v-input__append-outer i")
                .last()
            );
          }

          // 添加通用SKU
          $(".variation-option-creator:eq(0)").find("button").eq(0).click();
          await addSku(0, generalSku);
          await wait(timeout);
          resolve();
          return;
        }

        /** 2个SKU */
        // 获取次要SKU的数量，不包括（通用）
        for (var ai = 0; ai < arr.length; ai++) {
          if (
            arr[ai].getElementsByTagName("input")[0].value ==
            pddData.filterSkuKind
          ) {
            minorSkuSize = $(".variation-option-creator:eq(" + ai + ")").find(
              ".v-input__append-outer i"
            ).length;
          }
        }

        // 第一个SKU不能超过25个
        for (var ai = 0; ai < arr.length; ai++) {
          if (
            arr[ai].getElementsByTagName("input")[0].value !=
            pddData.filterSkuKind
          ) {
            let more =
              $(".variation-option-creator:eq(" + ai + ")").find(
                ".v-input__append-outer i"
              ).length - 25;
            for (var i = 0; i < more; i++) {
              await deleteSku(
                $(".variation-option-creator:eq(" + ai + ")")
                  .find(".v-input__append-outer i")
                  .last()
              );
            }
            moreSkuSize = Math.floor(
              50 /
              $(".variation-option-creator:eq(" + ai + ")").find(
                ".v-input__append-outer i"
              ).length
            );
          }
        }

        for (var ai = 0; ai < arr.length; ai++) {
          if (
            arr[ai].getElementsByTagName("input")[0].value ==
            pddData.filterSkuKind
          ) {
            subSkuIndex = ai;

            goods = pddData.goods;

            // 获取最低价
            let miniPrice = goods[0].targetPrice;
            let maxPriceIndex = 0;
            // 遍历第几个后是5倍内，并获取其索引
            for (var gi = 0; gi < goods.length; gi++) {
              maxPriceIndex =
                goods[gi].targetPrice < 5 * miniPrice ? gi : maxPriceIndex;
            }

            // 重新拆分goods
            goods = goods.slice(0, maxPriceIndex + 1);

            let goodsLength = goods.length;
            let kyyGoods = $(".variation-option-creator:eq(" + ai + ")").find(
              '.v-text-field__slot input[aria-label="选项"]'
            );
            let kyySkuLength = kyyGoods.length;
            let isExist = false;
            let delArr = [];

            // 排除无效的SKU
            for (var k = 0; k < kyySkuLength; k++) {
              isExist = false;
              for (var j = 0; j < goodsLength; j++) {
                if (kyyGoods.eq(k).val() == goods[j].sku) {
                  isExist = true;
                  break;
                }
              }
              if (!isExist) {
                delArr.unshift(k);
              }
            }

            // 删除掉无效的sku，从后往前删
            for (var di = 0; di < delArr.length; di++) {
              await deleteSku(
                $(".variation-option-creator:eq(" + ai + ")")
                  .find(".v-input__append-outer i")
                  .eq(delArr[di])
              );
            }

            // 排序多余的SKU
            if (goodsLength > moreSkuSize - 1) {
              let moreLength = goodsLength - (moreSkuSize - 1);
              while (moreLength--) {
                await deleteSku(
                  $(".variation-option-creator:eq(" + ai + ")")
                    .find(".v-input__append-outer i")
                    .last()
                );
              }
            }

            // 添加通用SKU
            $(".variation-option-creator:eq(" + ai + ")")
              .find("button")
              .eq(0)
              .click();
            await addSku(ai, generalSku);
          }
        }
        await wait(timeout);
        resolve();
        break;
      }
      default: {
        console.log("initSku error");
        break;
      }
    }
  });
}